<?php
/**
 * Created by PhpStorm.
 * User: Yiranleer
 * Date: 2017/1/11
 * Time: 10:55
 */
namespace Home\Controller;
use Think\Controller;

class WeController extends Controller {

    private $_config = array(
        'appid' =>  'wxe535a0a4a23d55e5',
        'appsecret' =>  '5d17b48c7672e78ea85a2c51c924f037',
        'token' =>  'yiranleer',
        'encodingaeskey'    =>  ''
    );

    private $appid = 'wxe535a0a4a23d55e5';
    private $appsecret = '5d17b48c7672e78ea85a2c51c924f037';
    private $token = 'yiranleer';
    private $encodingaeskey = '';
    public function _initialize(){
        Vendor('Wechat.Loader');
    }

    public function index(){
        define("TOKEN", "yiranleer");
        if (!isset($_GET['echostr'])) {
            $this->responseMsg();
        }else{
            $this->valid();
        }
    }

    public function valid(){
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg(){
        if($this->checkSignature()){
            $postStr = $GLOBALS['HTTP_RAW_POST_DATA'];
            if(!empty($postStr)){
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
//                $fromUsername = $postObj->FromUserName;//发送人
//                $toUsername = $postObj->ToUserName;//接收人
                $MsgType = trim($postObj->MsgType);//消息类型
//                $MsgId = $postObj->MsgId;//消息id
//                $time = time();//当前时间做为回复时间

                switch ($MsgType){
                    case 'text':
                        $result = $this->responseText($postObj);
                        break;
                    case 'image':
                        $result = $this->responseImage($postObj);
                        break;
                    default:
                        echo '';
                        exit();
                }

                echo $result;
            }
        }
    }

    /**
     * 记录日志
     * @param $str
     * @param $mode
     */
    function log($str){
        $mode='a';//追加方式写
        $file = "log.txt";
        $oldmask = @umask(0);
        $fp = @fopen($file,$mode);
        @flock($fp, 3);
        if(!$fp)
        {
            Return false;
        }
        else
        {
            @fwrite($fp,$str);
            @fclose($fp);
            @umask($oldmask);
            Return true;
        }
    }
    private function responseText($postObj){

        $content = trim($postObj->Content);
        $msg = '';

        switch ($content){
            case "你好":
                $msg .= '你好';break;
            case "打酱油":
                $msg .= '一斤酱油';break;
            case "测试":
                $msg .= '测试';break;
            default:
                $msg  =  '您好，请输入正确的话语';break;
        }

        $newsTpl = "<xml>
<ToUserName><![CDATA[%s]]></ToUserName>
<FromUserName><![CDATA[%s]]></FromUserName>
<CreateTime>%s</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[%s]]></Content>
</xml>";
        $sendMsg = sprintf($newsTpl,$postObj->FromUserName,$postObj->ToUserName,time(),$msg);
        $this->log($sendMsg);

        return $sendMsg;
    }
    private function responseImage($postObj){


    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }


    public function createMenus(){

        $menu_class = & \Wechat\Loader::get('Menu',$this->_config);


//        $access_token = getAccessToken($this->appid,$this->appsecret);

//        $menu_get = 'https://api.weixin.qq.com/cgi-bin/menu/get?access_token='.$access_token;
//        var_dump(request_get($menu_get));die;
        $menu = array(
            'button'=>array(
                array(
                    'name'  =>  '查询配方1',
                    'type'  =>  'click',
                    'key'   =>  'V1001_SEARCH_FORMULA'
                ),
                array(
                    'name'  =>  '查询材料2',
                    'type'  =>  'click',
                    'key'   =>  'V1001_SEARCH_MATERIALS',
                    'sub_button'    =>  array(
                        array(
                            'name'  =>  '删除菜单',
                            'type'  =>  'click',
                            'key'   =>  'V1001_NORMAL_MATERIALS',
                            'url'   =>  U('We/delMenu')
                        ),
                        array(
                            'name'  =>  '神级材料',
                            'type'  =>  'click',
                            'key'   =>  'V1001_GOD_MATERIALS',
                            'url'   =>  U('index/index')
                        ),
                        array(
                            'name'  =>  '神级材料1',
                            'type'  =>  'click',
                            'key'   =>  'V1001_GOD_MATERIALS',
                            'url'   =>  'www.qq.com'
                        )
                    )
                )
            ),

        );

        $result = $menu_class->createMenu($menu);
        var_dump($result);
//        $create_menu_url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
//        $result = request_post($create_menu_url,preg_replace_callback('/\\\\u([0-9a-f]{4})/i', create_function('$matches', 'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'), json_encode($menu)));
//        $result = request_post($create_menu_url,json_encode($menu,JSON_UNESCAPED_UNICODE));
//        var_dump($result);
    }

    public function delMenu(){

        $menu_class = & \Wechat\Loader::get('Menu',$this->_config);
        $result = $menu_class->deleteMenu();

    }


}